<template>
  <div>
    <div class="title"> {{"阶段配置 - ["+phaseData.name + "]"}}</div>
    <el-form :model="phaseData" label-width="70px" ref="ruleForm" size="mini" :hide-required-asterisk="true">
      <el-row :gutter="24">
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段名称">
            <el-input v-model="phaseData.name" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段类型">
            <el-input v-model="phaseData.phaseType" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label="阶段编码">
            <el-input v-model="phaseData.sn" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="23" :sm="12" :md="12" :lg="6" :xl="6">
          <el-form-item label-width="0" style="text-align: right;" class="btnGourd">
            <el-button type="primary" size="mini" @click="handleAdd()">添 加</el-button>
            <el-button type="primary" size="mini" @click="handleEdit()">编 辑</el-button>
            <el-button type="primary" size="mini" @click="handleDel()">删 除</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <el-row :gutter="24">
          <el-col :xs="24">
            <div class="tableAuto">
              <el-table :data="tableData" :height="height" @row-click="rowClick" style="width:100%" border stripe v-loading="tableLoading"
                :header-cell-style="{background:'#EAEBEC'}" ref="refTable" highlight-current-row>
                <el-table-column label="" width="50" align="center">
                  <template slot-scope="scope">
                    <div>
                      <el-radio :label="scope.row.fid" v-model="radioId">&nbsp;</el-radio>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
                <el-table-column prop="itemId" show-overflow-tooltip label="物料"></el-table-column>
                <el-table-column prop="qty" show-overflow-tooltip label="投料量"></el-table-column>
                <el-table-column prop="hi" show-overflow-tooltip label="上限"></el-table-column>
                <el-table-column prop="lo" show-overflow-tooltip label="下限"></el-table-column>
                <el-table-column prop="uom" show-overflow-tooltip :label="$t('basic.company')"></el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :xs="24">
            <div class="pagination-area">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 20, 50, 100]"
                :page-size="pagerTab.pageSize" :current-page="pagerTab.pageNum" layout="total, sizes, prev, pager, next, jumper"
                :total="pagerTab.total">
              </el-pagination>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="23" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="备注">
              <el-input type="textarea" rows="2" v-model="phaseData.description" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="footerBtn">
      <el-button type="primary" size="small" :loading="loading"
        @click="handleConfirmStorage('ruleForm')">{{ $t("common.preservation") }}</el-button>
      <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
    </div>

    <el-dialog :title="title" v-dialogDrag :visible.sync="isAddDialog" :close-on-click-modal="false" :before-close="handleCloseAdd"
      :width="screenWidth > 1024 ? '30%' : '35%'">
      <el-form :model="ruleForm" label-width="85px" ref="formName" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="35">
          <el-col :xs="24">
            <el-form-item label="物料名称" prop="itemId" class="material">
              <el-select v-model="ruleForm.itemId" remote filterable :remote-method="remoteMethodMaterial" placeholder=""
                v-el-select-loadmore="loadMoreMaterialFun" clearable @clear="clearMaterial" @change="changeItemId">
                <el-option v-for="(item,index) in materialList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="数量" prop="qty">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.qty" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item :label="$t('basic.company')" prop="uom">
              <el-input type="text" disabled v-model="ruleForm.uom" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="上限" prop="hi">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.hi" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="下限" prop="lo">
              <el-input type="number" v-enterNumber2 v-model="ruleForm.lo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="loadingTab"
          @click="handleConfirm('formName')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleCloseAdd()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>
  </div>

  </div>
</template>

<script>
import { configure } from "@/api/configure"
import { formula } from "@/api/formula"
export default {
  props: {
    screenWidth: Number,
    isShow: Boolean,
    phaseData: Object,
    parentFid: String
  },
  data () {
    let HiFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(this.ruleForm.qty) > parseInt(value)) {
          callback(new Error('物料上限不能小于物料数量'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let LoFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(value) > parseFloat(this.ruleForm.qty)) {
          callback(new Error('物料下限不能大于物料数量'));
        } else if (this.ruleForm.hi) {
          if (parseFloat(value) > parseFloat(this.ruleForm.hi)) {
            callback(new Error('物料下限不能大于物料上限'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      height: "calc(100vh - 375px)",
      radioId: "",
      title: "",
      tableData: [],
      materialList: [],
      isAddDialog: false,
      tableLoading: false,
      loading: false,
      loadingTab: false,
      ruleForm: {
        itemId: "",
        qty: "",
        uom: "",
        hi: "",
        lo: "",
        seq: "",
      },
      rules: {
        itemId: [{ required: true, message: '物料名称不能为空', trigger: 'change' }],
        qty: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
        hi: [{ validator: HiFn, trigger: 'blur' }],
        lo: [{ validator: LoFn, trigger: 'blur' }]
      },
      pagerTab: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      pager: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      keyword: ""
    }
  },
  created () {
    this.getItemList()
    this.phaseAdmList()
  },
  methods: {
    phaseAdmList () {
      const param = {
        phaseId: this.parentFid,
        page: this.pagerTab.pageNum,
        size: this.pagerTab.pageSize
      }
      this.tableLoading = true
      formula.phaseAdmList(param).then(res => {
        this.tableLoading = false
        if (res.code == 200) {
          this.tableData = res.data.rows
          this.pagerTab.total = res.data.total
        }
      })
    },
    getItemList () {
      const param = {
        className: this.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        itemClassVo: {
          consumed: 1
        }
      }
      configure.getItemList(param).then(res => {
        console.log(111)
        if (res.code == 200) {
          this.materialList = [...this.materialList, ...res.data.rows]
        }
      })
    },
    handleAdd () {
      this.ruleForm = {}
      try {
        this.$refs['formName'].resetFields();
      } catch (e) { }
      this.title = "添加"
      this.isAddDialog = true
    },
    handleCloseAdd () {
      this.isAddDialog = false
    },
    handleEdit () {
      if (this.radioId === '') {
        this.$message.error('请选择修改数据');
        return
      }
      this.title = "编辑"
      formula.findPhaseAdm(this.radioId).then(res => {
        if (res.code == 200) {
          this.ruleForm = Object.assign({}, res.data)
          this.isAddDialog = true
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    handleDel () {
      if (this.radioId === '') {
        this.$message.error('请选择要删除的数据');
        return
      }
      formula.findPhaseAdm(this.radioId).then(res => {
        if (res.code == 200) {
          let fid = res.data.fid
          let that = this
          this.$customConfirm({
            onok () {
              formula.phaseAdmRemove(fid).then(res => {
                if (res.code == 200) {
                  that.phaseAdmList()
                  that.radioId = ''
                  that.$message({ duration: 1000, type: 'success', message: '删除成功!' });
                }
              })
            }
          });
        }
      })
    },
    rowClick (row) {
      this.radioId = row.fid;
      this.$refs.refTable.setCurrentRow(row)
    },
    handleConfirmStorage (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {
            fid: this.phaseData.fid,
            name: this.phaseData.name,
            type: this.phaseData.type,
            sn: this.phaseData.sn,
            description: this.phaseData.description,
          }
          this.loading = true
          configure.phaseDefineAdd(param, '编辑').then(res => {
            this.loading = false
            if (res.code == 200) {
              this.$message({ duration: 1000, type: 'success', message: '保存成功!' });
              this.$emit('uptionList')
            }
          }).catch(e => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    handleClose () {
      this.$emit('handleClose', 'PH_ADM')
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let param = {}
          if (this.title == '添加') {
            param = {
              itemId: this.ruleForm.itemId,
              uom: this.ruleForm.uom,
              qty: this.ruleForm.qty,
              phaseId: this.parentFid,
              lo: this.ruleForm.lo,
              hi: this.ruleForm.hi,
            }
          } else {
            param = Object.assign({}, this.ruleForm)
          }
          this.loadingTab = true
          formula.phaseAdmAdd(param, this.title).then(res => {
            this.loadingTab = false
            if (res.code == 200) {
              this.isAddDialog = false
              this.phaseAdmList()
            } else {
              this.$message.error(res.msg);
            }
          })
        } else {
          return false
        }
      })
    },
    changeItemId (val) {
      this.ruleForm.uom = this.materialList.find(item => item.fid == val).uomId
    },
    handleSizeChange (val) {
      this.pagerTab.pageSize = val
      this.phaseAdmList()
    },
    handleCurrentChange (val) {
      this.pagerTab.pageNum = val;
      this.phaseAdmList()
    },
    remoteMethodMaterial (keyword) {
      this.keyword = keyword.trim();
      this.pager.pageNum = 1
      setTimeout(() => {
        this.materialList = []
        this.getItemList()
      }, 200)
    },
    loadMoreMaterialFun () {
      this.pager.pageNum++
      this.getItemList()
    },
    clearMaterial () {
      this.keyword = ""
      this.pager.pageNum = 1
      this.materialList = []
      this.getItemList()
    },
  }
}
</script>

<style scoped>
.pagination-area {
  padding: 10px;
}
.material >>> .el-select {
  width: 100%;
}
.title {
  line-height: 35px;
  background: #3b2e58;
  color: #fff;
  padding: 0 15px;
  font-size: 14px;
  margin-bottom: 10px;
}
.footerBtn {
  text-align: right;
}
</style>